const jwt = require('jsonwebtoken')
const fetch = require('isomorphic-fetch')

function getUserId (ctx) {
  console.log(ctx.request.headers)
  const Authorization = ctx.request.get('Authorization')
  if (Authorization) {
    const token = Authorization.replace('Bearer ', '')
    const { userId } = jwt.verify(token, process.env.APP_SECRET)
    return userId
  }

  throw new AuthError()
}

const queryWithBody = async (path, body) => {
  const res = await fetch(process.env.TEXT_SERVER + path, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify(body)
  })
  return res.json()
}

class AuthError extends Error {
  constructor () {
    super('Not authorized')
  }
}

class PermissionError extends Error {
  constructor () {
    super('Permission Error')
  }
}

class ExistsNameError extends Error {
  constructor () {
    super('Exists Name Error')
  }
}

module.exports = {
  getUserId,
  AuthError,
  PermissionError,
  ExistsNameError,
  queryWithBody
}
